(function() {
  var HIDE_DELAY = 3000;
  var $tip = $('#tip');
  var $fieldTip = $('#field-tip-wrapper');
  var $shortcutDeletionTip = $('#shortcut-deletion-confirmation-wrapper');
  var $deleteShortcutBtn = $('#delete-shortcut-btn');
  var $cancelDeleteShortcutBtn = $('#cancel-delete-shortcut-btn');
  var $alsoDeleteShortcutCb = $('#also-delete-shortcut-cb');
  var shortcutDeletionCallback;
  
  var showTimer;
  var showFieldTimer;
  var tip = window.Tip = {
    setup: function() {
      $deleteShortcutBtn.on('click', function() {
        var alsoDeleteShortcut = $alsoDeleteShortcutCb.get().checked;
        if (alsoDeleteShortcut) {
          shortcutDeletionCallback('also_delete_shortcut');
        } else {
          shortcutDeletionCallback('not_delete_shortcut');
        }
        tip.hideShortcutDeletionConfirmation();
      });

      $cancelDeleteShortcutBtn.on('click', function() {
        shortcutDeletionCallback('cancel');
        tip.hideShortcutDeletionConfirmation();
      });
    },
    
    show: function(message) {
      clearTimeout(showTimer);
      $tip.text(message).attr('title', message).addClass('show');
      var left = (window.innerWidth - $tip.get().clientWidth) / 2;
      left = left < 0 ? 0 : left;
      $tip.css('left', left + 'px');
      showTimer = setTimeout(function() {
        tip.hide();
      }, HIDE_DELAY);
    },

    hide: function() {
      $tip.removeClass('show');
    },

    alert: function(type) {
      var message = i18n[type];
      tip.show(message);
    },

    showFieldTip: function(field, message) {
      clearTimeout(showFieldTimer);
      $fieldTip.show().addClass('show');
      $('#field-tip').attr('title', message).text(message);
      var top = field.offsetTop - $fieldTip.get().offsetHeight - 10;
      var left = field.offsetLeft;
      $fieldTip.css({
        top: top + 'px',
        left: left + 'px'
      });
      showFieldTimer = setTimeout(function() {
        tip.hideFieldTip();
      }, HIDE_DELAY);
    },

    hideFieldTip: function() {
      $fieldTip.removeClass('show');
    },

    alertField: function(field, type) {
      var message = i18n[type];
      tip.showFieldTip(field, message);
      return false;
    },

    confirm: function(type) {
      return confirm(i18n[type]);
    },

    confirmToDeleteShortcut: function(callback) {
      shortcutDeletionCallback = callback;
      $alsoDeleteShortcutCb.get().checked = false;
      $.setDialogPosition($shortcutDeletionTip.get());
      $shortcutDeletionTip.show();
      Manager.showOverlay();
    },

    hideShortcutDeletionConfirmation: function() {
      $shortcutDeletionTip.hide();
      Manager.hideOverlay();
    }
  };
})();